package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO 登录信息
     * @return Employee
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1. 根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 2. 使用MD5对密码加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // 3. 密码比对
        if (!encryptedPassword.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 4. 检查账号状态
        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 5. 返回实体对象
        return employee;
    }


    /**
     * 修改密码
     *
     * @param passwordEditDTO 修改密码DTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        // 根据当前线程的上下文，获取当前登录用户id
        Long empId = BaseContext.getCurrentId();
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();

        // 获取当前员工信息
        Employee employee = employeeMapper.getById(empId);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 使用MD5加密旧密码进行比对
        String encryptedOldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!employee
                .getPassword()
                .equals(encryptedOldPassword)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 使用MD5加密新密码并更新
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        employee.setPassword(encryptedNewPassword);

        // 修改员工信息，持久化
        employeeMapper.update(employee);
    }


    /**
     * 修改员工状态
     *
     * @param status 状态
     * @param id     员工id
     */
    @Override
    public void status(Integer status, Long id) {
        // 1.创建员工对象，设置属性
        Employee employee = Employee
                .builder()
                .id(id)
                .status(status)
                .build();

        // 2.修改员工信息
        employeeMapper.update(employee);
    }

    /**
     * 分页查询员工
     *
     * @param employeePageQueryDTO 分页查询DTO
     * @return List<Employee> 员工列表
     */
    @Override
    public PageResult<Employee> page(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1.设置分页参数
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        // 2.执行分页查询
        List<Employee> employeeList = employeeMapper.page(employeePageQueryDTO);
        Page<Employee> page = (Page<Employee>) employeeList;

        // 3.返回封装后的结果
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 新增员工
     *
     * @param employeeDTO 新增员工DTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        // 1.将DTO转换为实体对象
        BeanUtils.copyProperties(employeeDTO, employee);

        // 2.设置实体对象属性
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        // 3.保存员工信息
        employeeMapper.save(employee);
    }

    /**
     * 根据id查询员工
     *
     * @param id 员工id
     * @return 员工实体对象
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工信息
     *
     * @param employeeDTO 员工信息DTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        // 1.创建实体对象
        Employee employee = new Employee();

        // 2.将DTO转换为实体对象
        BeanUtils.copyProperties(employeeDTO, employee);

        // 3.修改员工信息
        employeeMapper.update(employee);
    }
}
